package org.logging.servletlistener;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //在项目启动第一次时创建，该项目只创建一次，唯一的
        ServletContext context = this.getServletContext(); 

        String url="/online/home.jsp";
        
        String username=request.getParameter("username");
        username=new String(username.getBytes("ISO-8859-1"));
        
        //获取用户列表,第一次获取时候为空   
        ArrayList<String> users=(ArrayList<String>)context.getAttribute("users"); 
        //第一个用户登录时
        if(users==null){
            users = new ArrayList<String>();     
            users.add(username);   
            context.setAttribute("users", users);   //将第一个用户的名字保存到ServletContext对象中   
            HttpSession session = request.getSession();
            String id = session.getId();
            
        //非第一个用户登录   
        }else{
            for(String user : users){
                //如果该用户已经登录,请求error.jsp不让其再登录
                if(username.equals(user)){
                    url = "/online/error.jsp";   
                    break;   
                }
            }
            //如果该用户没登录,就将该用户的名字保存到ServletContext对象中
            users.add(username); 
        }
        
        request.getSession().setAttribute("user", username);   //保存一下该用户信息以备后用   
        response.sendRedirect(url);   
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}